/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import entity.News;
import java.io.File;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import model.NewsModel;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author VANANH
 */
public class ParseXml {

    public static boolean parser() {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new File("tapchilaptrinh.xml"));

            XPathFactory xpathFactory = XPathFactory.newInstance();
            XPath xPath = xpathFactory.newXPath();

            NodeList items = (NodeList) xPath.evaluate("//item", document, XPathConstants.NODESET);
            for (int i = 0; i < items.getLength(); i++) {
                Node node = items.item(i);
                NodeList childs = node.getChildNodes();
                News n = null;
                String title = null;
                String link = null;
                String author = null;
                String description = null;
                String pubDate = null;
                
                for (int j = 0; j < childs.getLength(); j++) {
                    Node child = childs.item(j);

                    if (child.getNodeName().equals("title")) {
                        title = child.getTextContent();
                    }
                    if (child.getNodeName().equals("link")) {
                        link = child.getTextContent();
                    }
                    if (child.getNodeName().equals("dc:creator")) {
                        author = child.getTextContent();
                    }
                    if (child.getNodeName().equals("description")) {
                        description = child.getTextContent();
                    }
                    if (child.getNodeName().equals("pubDate")) {
                        pubDate = child.getTextContent();
                    }
                }
                n = new News(title, link, author, description, pubDate);
                NewsModel.addNewsItem(n);
            }
            return true;
        } catch (Exception ex) {
            Logger.getLogger(ParseXml.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }
}
